import arrow

from app.db.models.notifications import Notifications
from flask import request, g


class Mail(object):
    def __init__(self, mail_type, mode):
        request_args = request.args
        uid = g.user.id
        self.mail_type = mail_type
        self.mode = mode
        self.page = int(request_args.get('page', 1))
        self.limit = int(request_args.get('limit', 10))

        if mode == 'mini':
            self.allow_key = ('id', 'datetime', 'title')
            self.base_query = {f'isMarkedMap__{uid}': False}
            self.limit = 5
        else:
            self.allow_key = ()
            self.base_query = {}

        self._get_func = {
            'warnings': self._get_warnings,
            'system': self._get_systems
        }

    def _get_warnings(self, category='告警通知'):
        data = Notifications.objects.filter(
            category=category, **self.base_query).only(*self.allow_key).order_by('-datetime')
        new_data = []
        for item in data[:self.limit]:
            _temp_dict = {k: getattr(item, k, '') for k in self.allow_key}
            if _time := item.datetime:
                _temp_dict['datetime'] = arrow.get(_time).isoformat()
            _temp_dict['id'] = str(item['id'])
            _temp_dict['isMarked'] = False
            new_data.append(_temp_dict)

        return new_data, len(data)

    def _get_systems(self):
        return self._get_warnings(category='服务公告')

    def get(self):
        if func := self._get_func[self.mail_type]:
            data, count = func()
            return {'data': data, 'count': count, 'page': self.page}
        return {'data': {}, 'count': 0, 'page': 1}
